package com.suanfa.linkedlist;

import java.util.Iterator;

public class DoublyLinkedListSentinel implements Iterable<Integer>{
    static class Node{
        Node prev;
        int value;
        Node next;


        public Node(Node prev, int value,Node next){
            this.prev=prev;
            this.value=value;
            this.next=next;
        }
    }
    private Node head;
    private Node tail;




    public DoublyLinkedListSentinel(){
        head=new Node(null,0,null);
        tail=new Node(null,0,null);
        head.next=tail;
        tail.prev=head;
    }

    private Node findNode(int index){
        int i = -1;
        for(Node p=head;p!=null;p=p.next,i++){
            if(i==index){
                return p;
            }
        }
        return null;
    }

    public void insert(int index,int value){
        Node prev=findNode(index);
        if(prev==null){
            throw new RuntimeException();
        }
        Node next=prev.next;
        Node inserted = new Node(prev,value,next);
        prev.next=inserted;
        next.prev=inserted;
    }

    public void remove(int index){
        Node prev = findNode(index-1);
        if(prev==null){
            throw new RuntimeException();
        }
        Node removed =prev.next;
        if (removed==tail){
            throw new RuntimeException();
        }
        Node next = removed.next;
        prev.next=removed.next;
        next.prev=prev;
    }

    public void addLast(int value){
        Node last = tail.prev;
        Node added = new Node(last,value,tail);
        tail.prev=added;
        last.next=added;
    }

    public void removeLast(){
        Node removed = tail.prev;
        if(removed==head){
            throw new RuntimeException();
        }

        Node prev =removed.prev;
        tail.prev=prev;
        prev.next=tail;

    }





    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            Node p = head.next;
            @Override
            public boolean hasNext() {
                return p.next!=null;
            }

            @Override
            public Integer next() {
                int value = p.value;
                p=p.next;
                return value;
            }
        };
    }
}
